<template>
    <div>
        <el-tabs type="card" @tab-click="handleTabClick">
                <el-tab-pane :label="item.name" v-for="(item, index) in formtable" :key="index" >
                    <div style="padding:10px 20px;">    
                       <div v-if="item.istable">
                          <label v-for="(itemw, i) in item.subitem" :key="i" style="display:inline-block;margin:0 10px;">
                            <el-button type="text" :icon="itemw.icon" @click="getWlClick(itemw.value, index + 1, item)" :disabled="disableds">{{ itemw.name }}</el-button>
                          </label>
                       </div>
                    </div>
                    <div v-if="item.value=='image'">
                        <el-upload
                            :http-request="uploadServerLog"
                            :show-file-list="false"
                            action="##"
                            class="upload-demo mr10 mb15"
                            multiple >
                            <div style="vertical-align: middle;margin-top:8px;">
                            <label v-if="imageUrl && imageUrl.length > 0" style="display:inline-block;height:50px;margin:10px;vertical-align:top;">
                                <img v-for="(item, index) in imageUrl" :key="index" :src="item.url" class="img" style="width:50px;" />
                            </label>
                            <label style="display:inline-block;border:3px dashed #999;border-radius: 8px;width:50px;height:50px;margin:10px;padding-top:4px;">
                                <i class="el-icon-plus avatar-uploader-icon" style="font-size:36px;font-weight:600;color:#999;"></i>
                            </label>
                            </div>
                        </el-upload>  
                    </div>
                    <div v-else style="position: relative;">
                        <div v-loading="tableLoading">
                           <drawerTables :selectDialogIndex="selectDialogIndex" :disabledfiled="disabledfiled" :keyName="item.value" :tableData="dangqianIndex==1 ? handlerFilterTime(item.allTableData[parentData.id], item.tableHeader) :item.allTableData[parentData.wuliaobianmaid]" :tableInfo="item.tableHeader" :zidianData="item.datadictList" @changeBack="changeTableBack" @selectTabel="selectTabel"></drawerTables>
                        <!-- {{parentData.wuliaobianmaid?parentData.wuliaobianmaid:parentData.id}} -->
                         <!-- {{ item.allTableData[parentData.wuliaobianmaid?parentData.wuliaobianmaid:parentData.id] }}  -->
                            
                        </div>
                        <div v-if="disableds" style="position: absolute;z-index:999;top:0;bottom:12px;width:100%;background-color: rgba(255,255,255,.1);"></div>
                    </div>
                </el-tab-pane>
        </el-tabs>
        <el-dialog :title="dialogtitle" :visible.sync="dialogVisible" width="60%" append-to-body>
            <selectDialog v-if="dialogVisible" :total="diatotal" :tableInfo="selectInfo" :tableData="selectData" :searchField="searchField" :searchForm="searchForm" @handlerSearch="handlerSearch" @handlerSubmit="handlerSubmit"></selectDialog>
        </el-dialog>
        <el-dialog :title="dialogliucheTitle" :visible.sync="dialogliucheVisible" width="80%" :top="dialogtop" append-to-body>
            <!-- <flowChart v-if="dialogliucheVisible" @hadnlerFlowMenu="hadnlerFlowMenu"></flowChart> -->
             <!-- <flowChartTest v-if="dialogliucheVisible"></flowChartTest> -->
            <flowChartTree v-if="dialogliucheVisible" :data="OrgTreeData" @hadnlerFlowMenu="hadnlerFlowMenu"></flowChartTree>
            <!-- <flowtree v-if="dialogliucheVisible"></flowtree> -->
        </el-dialog>
        <el-dialog :title="dialogFormliucheTitle"  width="50%" top="10vh" :visible.sync="dialogFlowVisible" append-to-body>
            <div style="margin-top:10px;" v-if="importTemplate.widgetList.length" >
                <VFormRender v-if="dialogFlowVisible"
                    ref="preForm"
                    :form-json="importTemplate"
                    :form-data="testFormData"
                    :preview-state="true"
                    :option-data="testOptionData"
                    :global-dsv="designerDsv"
                   
                    >
                </VFormRender>
            </div>
            <div style="padding:20px 0;">
                <el-button class="h32"  size="small" type="default" @click="dialogFlowVisible = false">取消</el-button>
                <el-button class="h32" size="small" type="primary" @click="saveFunData">保存</el-button>
            </div>
        </el-dialog>
    </div>
</template>
<script>
import { crudModuleListApi, crudModuleSaveDataApi,crudModuleUpdateApi, crudModuleInfoApi, crudModuleCreateApi,
    crudModuleFindApi, configDictDataApi, crudFormInfoApi, crudModuleBatchDelApi, crudModuleDelApi, databaseInfoApi } from '@/api/develop'
import { getDictDatainfoApi, getDictDataListApi } from '@/api/form'
import { uploader } from '@/utils/uploadCloud'
import drawerTables from '@/components/detailsEdit/table'
import selectDialog from '@/components/detailsEdit/selectDialog.vue'
import { EventBus } from '@/libs/bus'
import flowChart from './flowChart.vue'
import flowChartTree from './flowChatTree.vue'
import flowtree from './flowtree.vue'
import VFormRender from '@/components/form-render/index'

import { CLOSE_NODE_ICON_TOOLBAR } from '@/components/xmind-editor/event-constant'
import { contractCategorySelectApi } from '@/api/enterprise'
export default {
    name: 'HelloWorld',
    components: { drawerTables, selectDialog, flowChart, flowChartTree, VFormRender, flowtree },
    data() {
        return {
            tableLoading: true,
            tabactive:'1',
            imageUrl: [],
            percentShow: false,
            dialogtitle:'',
            dialogVisible: false,
            dialogliucheTitle: '流程图',
            dialogFormliucheTitle: '添加流程图',
            dialogliucheVisible: false,
            guigezidian: { // 规格字典搜索
                types: "guige",
                level: 1,
                pid:'',
                name:'', 
            },
            shitibiaosearch:{
                is_field_all:'',
                is_system:1,
                limit: 100,
                order_by:{},
                page:1,
                scope_frame:'all',
                show_search_type:'0',
                view_search: [],
                view_search_boolean:'',
            },
            selectInfo: [], // 弹窗表头信息
            selectData: [], // 弹窗表格数据
            searchField:[ {
                field_name:'代码或名称',
                field_name_en:'name',
                form_value:'input',
                placeholder:'请输入代码或名称关键字'
            }],
            searchForm: {
                name:''
            },
            selectDialogIndex: 1, // 选中弹窗表格索引默认为1,如果用数组索引测减1
            optionStatus:[],// 状态选择
            formtable: [], // 表单表格数据
            selectName:'', // 选中数据表名称

            dictForm: {
                types: '',
                level: 1,
                pid:''
            },
            selectFiledData: {

            },
            diatotal: 0,
            tabIndexs: 0,
            dialogtop: '5vh',
            dialogFlowVisible: false,
            importTemplate: {
                formConfig: {},
                widgetList: []
            },
            testFormData: {},
            testOptionData: {},
            OrgTreeData: {},
            liuchetuId: 0, // 流程图id
            liuchetustatus: 1, // 1添加2编辑3删除
            adminUserInfo: {},
            deletenum: 100,
            gongyiData: [],
            processData: [],
            processFlows:[],
            disabledfiled: [],
            danqianliuchetuData: null,
            allgongyiTableData: [], // 所有工艺

            
            isdidactflag: 0, // 是否调用字典方法
            flowtreewldanobj: {}, // 流程图添加物料档案;
            assciation55: 1,
            peijianleixing123: 1,

            rowsdatatest: [],

        }
    },
    computed: {
        designerDsv() {
           return this.globalDsv
        }
    },
    props: {
        keyName: {
            type: String,
            default: ''
        },
        id: { // 档案id
           type: Number,
           default: 0
        },
        isSubmit: {
            type: Number,
            default: 0
        },
        formDataAll: {
            type: Array,
            default: ()=>{
                return []
            }
        },
        pagestatus: { // 判断是否显示表单
            type: Number, 
            default: 1
        },
        flagStatu: {
            type: Number,
            default: 0,
        },
        treeData: {
            type: [Array, Object],
            default: ()=>{
                return []
            }
        },
        parentData: {
            type: Object,
            default: ()=>{
                return {}
            }
        },
        dangqianIndex: { // 工艺流程层级
            type: Number, 
            default: 1
        },
        disableds: {
            type: Boolean,
            default: false,
        }
       
    },
    watch: {
        isSubmit: {
            deep: true,
            handler(newValue){
                if(newValue == 1){
                    this.wuinit();
                }
            }
        }
    },
    beforeDestroy() {
      EventBus.$off('event-tree-grandchild', this.handleEvent)
    },
    mounted(){
        let adminuser = JSON.parse(window.localStorage.getItem('userInfo'));
        this.adminUserInfo = adminuser;
        this.wuinit();
        EventBus.$on('event-tree-gongyi', this.handleGongyiEvent)
    },
    methods:{
        resetchildhandler(){
            if(this.formtable.length > 0){
                this.formtable.map((item)=>{
                    item.allTableData = {};
                    item.oldData = [];
                    item.tableData = [];
                })
                this.formtable = []
            }
            this.isdidactflag = 0;
        },
        async wuinit(){
            console.log("进入了",this.dangqianIndex,  this.parentData)
            this.tableLoading = true;
            this.formtable = this.formDataAll; 
            if(this.flagStatu){
                this.formtable[0].tableData = this.treeData;
                this.formtable[0].allTableData[this.parentData.id] = this.treeData;
                this.$set(this.formtable, this.formtable);
                this.tableLoading = false;
            }else{
                await this.hadnlerwlqdInofinit();
            }
            console.log("this.formtable", this.formtable)
            this.$emit("handlerisSubmitVal", 0)
        },
                // 初始化表格数据
        // tab切换
        async handleTabClick(event){
            // 异步初始化物料清单信息
            let i = event.index;
            this.selectDialogIndex = Number(i) + 1;
            this.tableData = this.formtable[i].tableData;
        },
        handleGongyiEvent(gongyi){
           this.gongyiData = gongyi;
        },
        // 获取表格数据及字典数据
        async hadnlerwlqdInofinit(){
            let clength = this.formtable.length;
            for(let i=0;i<this.formtable.length;i++){
                if(this.formtable[i].istable){
                    // this.formtable[i].tableData = []
                    this.formtable[i].deleteData = []
                    if(this.formtable[i].value){
                        let resdatas = await crudModuleInfoApi(this.formtable[i].value, 0);
                        await this.handlerallFiledData(resdatas, i)
                        if(this.id){ 
                            if(i ==0){ // 物料清单
                                let allobj = this.formtable[i].allTableData || {};
                                if(this.dangqianIndex==1){
                                    allobj[this.parentData.id] = this.treeData;
                                }else{
                                    allobj[this.parentData.wuliaobianmaid] = this.treeData;
                                }
                                this.formtable[0].tableData = this.treeData;
                                this.formtable[0].oldData = JSON.parse(JSON.stringify(allobj));
                                this.formtable[0].allTableData = allobj;
                                this.$set(this.formtable, this.formtable)
                            }else{
                               let allobj = this.formtable[i].allTableData || {};
                               if(this.formtable[i].value == 'gongyi'){
                                  this.formtable[i].search['wuliaodangan'] = this.parentData.wuliaobianmaid ? this.parentData.wuliaobianmaid : this.parentData.id;
                               }
                               if(JSON.stringify(allobj) == '{}'){
                                    let data = await crudModuleListApi(this.formtable[i].value, this.formtable[i].search);
                                    await this.handlerTableAllData(this.formtable[i].value, data, i, allobj);
                               }else{
                                  let isflag = 1;
                                  let pwid = this.parentData.wuliaobianmaid ? this.parentData.wuliaobianmaid : this.parentData.id;
                                  for(let s in allobj){
                                     if(pwid == s){
                                        isflag = 0;
                                     }
                                  }
                                  if(isflag==1){
                                     let data = await crudModuleListApi(this.formtable[i].value, this.formtable[i].search);
                                     await this.handlerTableAllData(this.formtable[i].value, data, i, allobj);
                                  }
                                
                               }
                               
                          

                            }
                            
                        }
                       
                    }
                }
                if(i == clength - 1){
                    this.isdidactflag = 1;
                }
            }
        },
       
        // 获取表头数据
        async handlerallFiledData(resdata, index){
            let showFieldData = resdata.data.showField;
            let searchFieldData = resdata.data.seniorSearch;
            let searchdefault = this.formtable[index].search;
            let objs = {},searchobj = {},dataictnamearr=[]
            let fileallData = [];
            for(let i=0;i < showFieldData.length;i++){
                if(this.formtable[index].value == 'gongyi' && showFieldData[i].field_name_en =='wuliaodangan'){ // 工艺流程
                   
                }else{
                    objs[showFieldData[i].field_name_en] = ''
                    objs.disabled = false;
                    if(searchFieldData.length > 0){
                        if(searchFieldData[i]){
                        searchobj[searchFieldData[i].field_name_en] = ''
                        }
                    }
                    if(showFieldData[i].field_name_en != 'fuwuliaobianmaid'){
                        fileallData.push(showFieldData[i]); // 在索引1的位置
                    }
                }   
            }
            // 物料清单数据
            if(this.keyName=='wuliaoqingdanbiao' && index==0){
                let obja = {
                    data_dict_id: 0,
                    field_name: "中文描述",
                    field_name_en: "item_depc",
                    form_value:'input'
                }
                let objb = {
                    data_dict_id: 0,
                    field_name: "单位",
                    field_name_en: "unitName",
                    form_value:'input',
                    disabled: true,
                }
                fileallData.splice(1, 0, obja); // 在索引1的位置
                fileallData.splice(2, 0, objb); // 在索引1的位置
            }
            // end
            this.formtable[index].form = objs;
            this.formtable[index].search = {...searchdefault, ...searchobj};
            this.formtable[index].tableHeader = fileallData;
            if(index == 0 ){
                this.tableLoading = false;
            }
            if(this.isdidactflag == 0){
               await this.handlerDict(this.formtable[index].tableHeader, index);
            }
            
        },
         // 表格展示数据
        async handlerTableAllData(keyname, data, index, allobj){
            if(data.status==200){
                let resdataList = data.data.list;
                let formlists = []
                for(let i=0;i < resdataList.length;i++){
                    let formlist =  JSON.parse(JSON.stringify(resdataList[i]))
                   
                    if(resdataList[i].laiyuan && resdataList[i].laiyuan.length > 0){ // 状态
                        formlist.laiyuan = (resdataList[i].laiyuan).join(',')
                    }
                    if(keyname=='wuliaoqingdanbiao'){ // 物料清单
                        if(resdataList[i].bibie && resdataList[i].bibie.length > 0){ // 币别
                            formlist.bibie = (resdataList[i].bibie).join(',')
                        }
                        if(resdataList[i].wuliaodanganid){
                            let wlbmobj = { id: this.id, name: resdataList[i].wuliaodanganid || '' }
                            formlist.wuliaodanganid = wlbmobj
                        }
                        if(resdataList[i].wuliaoleibiebianmaid){
                            let wlbmobj = { id: this.id, name: resdataList[i].wuliaoleibiebianmaid || '' }
                            resdataList[i].wuliaoleibiebianmaid = wlbmobj
                        }
                    }else if(keyname == 'gongyi'){ // 工艺流程
                        formlist.wuliaodanganid = this.parentData.wuliaobianmaid ? this.parentData.wuliaobianmaid : this.parentData.id;
                        if(resdataList[i].baogong){
                            formlist.baogong = Number(resdataList[i].baogong)
                        }
                        if(resdataList[i].laiyuan && resdataList[i].laiyuan.length > 0){ // 来源
                            formlist.laiyuan = resdataList[i].laiyuan.join(',')
                        }else{
                            formlist.laiyuan = ''
                        }
                        if(resdataList[i].peijianleixing && resdataList[i].peijianleixing.length > 0){ // 配件类型
                            formlist.peijianleixing = (resdataList[i].peijianleixing).join(',')
                        }else{
                            formlist.peijianleixing  = ''
                        }
                        if(resdataList[i].daopeijianleixing && resdataList[i].daopeijianleixing.length > 0){ // 配件类型
                            formlist.daopeijianleixing = (resdataList[i].daopeijianleixing).join(',')
                        }else{
                            formlist.daopeijianleixing = ''
                        }
                        if(resdataList[i].bengongxuid){ // 本工序
                            let imdata = this.formtable[index].datadictList.bengongxuid;
                            if(imdata && imdata.length > 0){
                                for(let s=0;s<imdata.length;s++){
                                    if(resdataList[i].bengongxuid == imdata[s].gongxudaima || resdataList[i].bengongxuid == imdata[s].zhongwenmiaoshu || resdataList[i].bengongxuid == imdata[s].id){
                                        formlist.bengongxu = imdata[s].zhongwenmiaoshu;
                                        formlist.bengongxuid = Number(imdata[s].id);
                                        break;
                                    }
                                }
                            }
                        }
                        if(resdataList[i].daogongxuid){ // 到工序
                            let imdata = this.formtable[index].datadictList.bengongxuid;
                            if(imdata && imdata.length > 0){
                                for(let s=0;s<imdata.length;s++){
                                    if(resdataList[i].daogongxuid == imdata[s].gongxudaima || resdataList[i].daogongxuid == imdata[s].zhongwenmiaoshu || resdataList[i].daogongxuid == imdata[s].id){
                                        formlist.daogongxu = imdata[s].zhongwenmiaoshu
                                        formlist.daogongxuid = Number(imdata[s].id);
                                        break;
                                    }
                                }
                            }
                        }
                    }
                    
                    formlists.push(formlist)
                }
                let formlistnew = [], newdata = []
                // this.formtable[index].tableData = JSON.parse(JSON.stringify(formlists));
                if(keyname == 'gongyi'){
                    formlistnew = this.generateProcessFlowsnew(formlists);
                    for(let i=0;i<formlistnew.length;i++){
                        let data2 = formlistnew[i];
                        for(let j=0;j<data2.length;j++){
                            newdata.push(data2[j]);
                        }
                    }
                    let pwid = this.parentData.wuliaobianmaid ? this.parentData.wuliaobianmaid : this.parentData.id;
                    allobj[pwid] = newdata;
                    this.formtable[index].oldData = JSON.parse(JSON.stringify(allobj));
                    this.formtable[index].allTableData = JSON.parse(JSON.stringify(allobj));
                    this.$set(this.formtable, this.formtable)
                }
                
                
            }
        },
        // 字典表和实体表数据查询
        async handlerDict(headerData, index){
          let itemdata = headerData;
          let obj = {}
          if(itemdata && itemdata.length > 0){
            for(let i=0;i<itemdata.length;i++){
                if(itemdata[i].data_dict_id){ // 字典表查询下拉选择框数据
                    let dataictnamearr = []
                    if(itemdata[i].data_dict_id==123){ // 配件类型
                        if(this.peijianleixing123 == 1){
                            // let datadict = await getDictDatainfoApi(itemdata[i].data_dict_id)
                            // dataictnamearr.push(datadict.data.ident);
                            dataictnamearr.push('peijianleixing');
                            this.dictForm.types = dataictnamearr;
                            let datadictDta = await getDictDataListApi(this.dictForm)
                            obj.peijianleixing = datadictDta.data.list;
                            obj.daopeijianleixing = datadictDta.data.list;
                            // obj.daopeijianleixing = datadictDta.data.list;
                            this.peijianleixing123 = 2;
                        }
                        
                    }else{ // 其他字典
                        obj[itemdata[i].field_name_en] = []
                        let datadict = await getDictDatainfoApi(itemdata[i].data_dict_id)
                        dataictnamearr.push(datadict.data.ident);
                        this.dictForm.types = dataictnamearr;
                        let datadictDta = await getDictDataListApi(this.dictForm)
                        obj[itemdata[i].field_name_en] = datadictDta.data.list;
                    }                    
                }else if(itemdata[i].association_crud_id && itemdata[i].field_name_en !='wuliaobianmaid'){ // 关联表选择查询
                    let database = null, tabbasename = null, datalist = null;
                    let searchForm = JSON.parse(JSON.stringify(this.shitibiaosearch));
                    if(itemdata[i].association_crud_id==55){ // 工序设置实体表
                        searchForm.gongxushezhifuxuan = [['1']];
                        if(itemdata[i].field_name_en=='bengongxuid' && itemdata[i].field_name_en == 'daogongxuid'){
                            if(this.assciation55 == 1){
                                // database = await databaseInfoApi(itemdata[i].association_crud_id)
                                // tabbasename = database.data.table_name_en;
                                datalist = await crudModuleListApi('gongxushezhong', searchForm);
                                obj.bengongxuid = datalist.data.list;
                                obj.daogongxuid = datalist.data.list;
                                this.assciation55 = 2;
                            } 
                        }else{
                            datalist = await crudModuleListApi('gongxushezhong', searchForm);
                            obj[itemdata[i].field_name_en] = datalist.data.list;               
                        }
                    }else{ // 其他实体表
                        database = await databaseInfoApi(itemdata[i].association_crud_id)
                        tabbasename = database.data.table_name_en;
                        datalist = await crudModuleListApi(tabbasename, searchForm);
                        obj[itemdata[i].field_name_en] = datalist.data.list;
                    }
                }
                
            }
            this.formtable[index].datadictList = obj;
            this.$set(this.formtable, this.formtable)
          }
        },
        // table返回数据
        changeTableBack(status, index, data){
            if(status==1){
                this.formtable[this.selectDialogIndex-1].tableData[index].laiyuan = data
            }else if(status == 2){ // 选择损耗返回
                this.formtable[this.selectDialogIndex-1].tableData[index].sunhaodaima = data.sunhaodaima;
                this.formtable[this.selectDialogIndex-1].tableData[index].sunhaoleixing = data.sunhaoleixing;
                if(data.sunhaoshezhibili){
                    this.formtable[this.selectDialogIndex-1].tableData[index].sunhao = data.sunhaoshezhibili;
                }
            }
        },
        // logicflow事件返回
        hadnlerFlowMenu(index, data){
           this.liuchetuId = data.id || '';
           this.liuchetustatus = index;
           this.danqianliuchetuData = null;
           if(index==1 || index==0){ // 添加
              this.danqianliuchetuData = data;
              this.dialogFormliucheTitle = '添加流程图'
              this.hadnlerFormInput('gongyi', index, data)
           }else if(index==2) {  // 编辑
                this.dialogFormliucheTitle = '编辑流程图'
                this.hadnlerFormInput('gongyi', index, data )
           } else if(index==3){ // 删除
                this.handlerDelGoyiChang(data);
           }
        },
        // 工艺流程图删除数据处理方法
        handlerDelGoyiChang(data){
            this.formtable[1].deleteData.push(data.id);
            // 工艺表格数据
            let tabledels = this.formtable[1].allTableData[data.wuliaodanganid];
            for(let i=0;i<tabledels.length;i++){
                if(data.id == tabledels[i].id){
                    tabledels.splice(i, 1)
                    break;
                }
            }
            this.formtable[1].allTableData[data.wuliaodanganid] = tabledels;
            // 工艺流程图数据
            let allgydata = this.allgongyiTableData;
            for(let i=0;i<allgydata.length;i++){
                if(data.id == allgydata[i].id){
                    allgydata.splice(i, 1);
                    break;
                }
            }
            this.$set(this.formtable, this.formtable);
            this.$set(this.allgongyiTableData, allgydata)
            this.handlerFlowTreeData(allgydata)
        },
        // 流程图添加
        saveFunData(){
            this.dialogFlowVisible = false;
            this.$refs['preForm'].getFormData()
            .then((formData) => {
                if (this.liuchetustatus == 1) { // 添加
                    let formliuche = {
                        id: '',
                        baogong: Number(formData.baogong), // 报工
                        beizhu: formData.beizhu || '', // 备注
                        bengongxuid: formData.bengongxuid.id, // 本工序
                        daogongxuid: formData.daogongxuid.id, // 到工序
                        bengongxu: formData.bengongxuid.name, // 本工序
                        daogongxu: formData.daogongxuid.name, // 到工序
                        daopeijianleixing: this.handlerPeijianleixi(formData.daopeijianleixing, this.formtable[this.selectDialogIndex-1].datadictList
.peijianleixing), // 到配件类型
                        gongjia: formData.gongjia, // 工价
                        gongyinandu: formData.gongyinandu, // 工艺难度
                        laiyuan: formData.laiyuan?formData.laiyuan[0]:'', // 来源
                        peijianleixing: this.handlerPeijianleixi(formData.peijianleixing, this.formtable[this.selectDialogIndex-1].datadictList
                        .peijianleixing), // 配件类型
                        peijianxuhao: formData.peijianxuhao, // 配件序号
                        shengchanzhouqi: formData.shengchanzhouqi, // 生产周期
                        wuliaodangan: this.flowtreewldanobj.id, // 物料档案
                        user_id: this.adminUserInfo.id
                    } 
                    this.formtable[1].allTableData[this.flowtreewldanobj.id].push(formliuche)
                    this.$set(this.formtable, this.formtable)
                    let gydata = JSON.parse(JSON.stringify(this.allgongyiTableData));
                    gydata.push(formliuche)
                    this.$set(this.allgongyiTableData, gydata)
                    this.handlerFlowTreeData(gydata)

                    // this.savaUpdateData('gongyi', formliuche, 0);
                } else { // 编辑
                    let formliuche = JSON.parse(JSON.stringify(formData));
                    formliuche.wuliaodangan = this.flowtreewldanobj;
                    let editdata = this.formtable[1].allTableData[this.flowtreewldanobj.id];
                    let dataeditnew = this.handlerUnitgongyiData(editdata, formData)
                    this.formtable[1].allTableData[this.flowtreewldanobj.id] = dataeditnew;
                    this.$set(this.formtable, this.formtable)
                    this.savaUpdateData('gongyi', formliuche, this.liuchetuId);
                    // let tabeldataallls = this.handlerUnitgongyiData(this.allgongyiTableData, formData);
                    // this.$set(this.allgongyiTableData, tabeldataallls)
                    // this.handlerFlowTreeData(tabeldataallls)
                   
                   
                }
            })
            .catch((error) => {
                this.$message.error("ding:",error)
            })
        },
        handlerUnitgongyiData(data, formData){
            let tabeldataallls = data;
            for(let i=0;i< tabeldataallls.length;i++){
                if(this.liuchetuId == tabeldataallls[i].id){
                    tabeldataallls[i].baogong = formData.baogong; // 报工
                    tabeldataallls[i].beizhu = formData.beizhu; // 报工
                    tabeldataallls[i].laiyuan = this.handlerPeijianleixi(formData.laiyuan, this.formtable[1].datadictList.laiyuan); // 来源
                    tabeldataallls[i].gongyinandu = formData.gongyinandu; // 工艺难度
                    tabeldataallls[i].gongjia = formData.gongjia; // 工价
                    tabeldataallls[i].daopeijianleixing = this.handlerPeijianleixi(formData.daopeijianleixing, this.formtable[1].datadictList.peijianleixing) // 到配件类型
                    tabeldataallls[i].shengchanzhouqi = formData.shengchanzhouqi; // 生产周期
                    tabeldataallls[i].bengongxu = formData.daogongxuid.name; // 本工序名称
                    tabeldataallls[i].bengongxuid = formData.bengongxuid.id; // 本工序id
                    tabeldataallls[i].daogongxuid = formData.daogongxuid.id; // 到工序id
                    tabeldataallls[i].daogongxu = formData.daogongxuid.name; // 本工序name
                    tabeldataallls[i].peijianxuhao = formData.peijianxuhao; // 配件序号
                    tabeldataallls[i].peijianleixing = this.handlerPeijianleixi(formData.peijianleixing, this.formtable[1].datadictList.peijianleixing); // 配件类型
                }
            }
            return tabeldataallls;
        },
        // 实体列表新增保存
        savaUpdateData(keyName, data, id=0) { 
            if(id != 0){ // 编辑
                crudModuleUpdateApi(keyName, id, data)
                .then((res) => {
                    if (res.status == 200) {
                       
                    }
                })
                .catch((err) => {

                })
            }else{ // 新增
                crudModuleSaveDataApi(keyName, data)
                .then((res) => {
                    if (res.status == 200) {
                        
                    }
                })
                .catch((err) => {

                })
            } 
        },
        
        handlerPeijianleixi(ids, data = [], index = 0) {
            if (!Array.isArray(ids) || !Array.isArray(data)) return '';        
            const targetId = ids.find(id => id);
            if (!targetId) return '';

            const foundItem = data.find(item => item.value === targetId);
            if (!foundItem) return '';

            switch(index) {
                case 1: return { id: foundItem.value, name: foundItem.name };
                case 2: return foundItem.value;
                default: return foundItem.name;
            }
        },
        // 流程图添加编辑方法
        async hadnlerFormInput(keyname, index, data){
            let obj = {}
            obj.id = 0;
            let findData = null;
            if(index != 0){ // 编辑
                if(data.id){
                   obj.id = data.id;
                   findData = await crudModuleFindApi(keyname, data.id)
                }
            }
            const res = await crudModuleCreateApi(keyname, obj)
            if (res.data.form_info && res.data.form_info.global_options) {
               this.$set(this.importTemplate, 'formConfig', res.data.form_info.global_options)
            }
            let resoption =  res.data.form_info.options;
            if(resoption.length > 0){
                for(let i=0;i< resoption.length;i++){
                    if(resoption[i].name == '物料档案'){
                        resoption.splice(i, 1)
                    }
                }
            }
            this.$set(this.importTemplate, 'widgetList', resoption)
            if (findData) {
               let moduleinfo = findData.data.module_info;
               this.flowtreewldanobj = moduleinfo.wuliaodangan;
               if(index==1){ // 添加
                 moduleinfo = this.hadnlerModuleInfo(findData.data.module_info, index, data) 
               } 
               this.$set(this, 'testFormData', moduleinfo)
            }
            this.dialogFlowVisible = true;
        },
        hadnlerModuleInfo(data, index ,sdata){

            let moduleinfo = {
                baogong: sdata.baogong, // 报工
                beizhu: '', // 备注
                bengongxuid: data.daogongxuid, // 本工序
                daogongxuid: '', // 到工序
                daopeijianleixing: '', // 到配件类型
                gongjia: '', // 工价
                gongyinandu: '', // 工艺难度
                laiyuan: this.handlerlaiyuan(sdata.laiyuan), // 来源
                peijianleixing: data.peijianleixing, // 配件类型
                peijianxuhao: Number(sdata.peijianxuhao + 1), // 配件序号
                shengchanzhouqi: '', // 生产周期
                wuliaodangan: data.wuliaodangan.id
            }
            
            return moduleinfo;
        },
       
        deepRemoveDuplicates(data) {
            const seen = new Map();

            function processNode(node) {
                // 深度拷贝避免修改原数据
                const newNode = { ...node };  
                // 处理子节点
                if (newNode.children && newNode.children.length) {
                const childMap = new Map();
                newNode.children = newNode.children
                    .map(child => processNode(child))
                    .filter(child => {
                    if (!childMap.has(child.peijianleixing)) {
                        childMap.set(child.peijianleixing, true);
                        return true;
                    }
                    return false;
                    });
                }

                return newNode;
            }

            // 处理根节点
            const rootMap = new Map();
            return data
                .map(node => processNode(node))
                .filter(node => {
                if (!rootMap.has(node.peijianleixing)) {
                    rootMap.set(node.peijianleixing, true);
                    return true;
                }
                return false;
                });
        },

        // 添加，选择，删除等方法
        async getWlClick(val, indexstatus=0, item){
            console.log("getWlClick:",val, indexstatus, item, this.parentData)
            this.selectDialogIndex = indexstatus;
            this.dialogtitle = item.name;
            if(val=='add'){ // 添加
                this.selectName = item.subitem[0].tablename;
                if(this.selectName=='guige'){ // 选择规格(规格字典表)
                   this.searchForm  = { name: ''}
                   this.searchField = [ {field_name_en: 'name', field_name:'代码或名称'}]; 
                   this.getGuigezidian(this.guigezidian, indexstatus);
                }else{ // 实体表
                    if(this.selectName){ // 根据从其他表添加数据
                        let resdatas = await crudModuleInfoApi(this.selectName, item.subitem[0].id || 0);
                        if(resdatas.status==200){
                            this.selectFiledData = resdatas.data;
                            this.getshitibiaosearch(this.selectName, this.formtable[indexstatus-1].search, indexstatus, resdatas.data);
                        }
                    }else{ // 直接添加数据
                        let pwid = this.parentData.wuliaobianmaid ? this.parentData.wuliaobianmaid : this.id;
                        let dataheader = this.formtable[indexstatus-1].tableHeader;
                        let tableLength = this.formtable[indexstatus-1].allTableData[pwid].length || 0;
                        let bengongxu = '', peijianxuhao='', peijianleixing = '';
           
                        if(tableLength > 0){
                          bengongxu = this.formtable[indexstatus-1].allTableData[pwid][tableLength-1].daogongxuid || '';
                          peijianxuhao =  this.formtable[indexstatus-1].allTableData[pwid][tableLength-1].peijianxuhao || '';
                          peijianleixing =  this.formtable[indexstatus-1].allTableData[pwid][tableLength-1].peijianleixing || ''
                        }
                        let laiyuan = ''
                        if(this.formtable[indexstatus-1].value=='gongyi'){ // 工艺流程表添加数据时，默认本工序为上一个工序的到工序
                            let imdata = this.formtable[indexstatus-1].datadictList.bengongxuid;
                            for(let i=0;i<imdata.length;i++){
                                if(bengongxu == imdata[i].gongxudaima || bengongxu == imdata[i].zhongwenmiaoshu ){
                                    if(imdata[i].laiyuan && imdata[i].laiyuan.length > 0){
                                        laiyuan = imdata[i].laiyuan.join(",")
                                    }else{
                                        laiyuan = '';
                                    }
                                    break;
                                }
                            }
                            
                        }
                        this.deletenum++;
                        let obj = {}
                        obj.deleteid = 'B' + this.deletenum
                        for(let i = 0; i < dataheader.length;i++){
                            obj.id = ''
                            if(dataheader[i].field_name_en == 'bengongxuid'){
                              obj[dataheader[i].field_name_en] = bengongxu
                            }else if(dataheader[i].field_name_en == 'laiyuan'){
                                obj[dataheader[i].field_name_en] = laiyuan
                            }else if(dataheader[i].field_name_en == 'peijianxuhao'){
                                obj[dataheader[i].field_name_en] = Number(peijianxuhao) + 1
                            }else if(dataheader[i].field_name_en == 'peijianleixing'){
                                obj[dataheader[i].field_name_en] = peijianleixing
                            }else{
                              obj[dataheader[i].field_name_en] = ''
                            }
                        }
                        
                        obj.wuliaodangan = pwid;
                        this.formtable[indexstatus-1].allTableData[pwid].push(obj)
                        // this.formtable[indexstatus-1].tableData.push(obj)
                        this.$set(this.formtable, this.formtable)
                    }
                }
            }else if(val=='select'){ // 选择
               this.selectName = this.keyName;
            //    let wldadatas = crudModuleListApi(this.keyName);
               this.dialogtitle = '从其他物料档案选择规格'
               this.dialogVisible = true;
               this.selectInfo = this.formtable[0].tableHeader;
            }else if(val=='delete'){ // 删除
                let pwd = this.dangqianIndex==1? this.parentData.id: this.parentData.wuliaobianmaid
                let newdata = [],newselectd=this.formtable[indexstatus-1].deleteData;
                let dataArray = this.formtable[indexstatus-1].allTableData[pwd];
                let selectids = this.formtable[indexstatus-1].selectData;
                if(selectids.length > 0){
                    for(let i=0; i< dataArray.length;i++){
                        if(this.formtable[indexstatus-1].value=='gongyi'){
                            if(dataArray[i].id){
                                if(!selectids.includes(dataArray[i].id)){ // 删除数据
                                    newdata.push(dataArray[i]);
                                }else{
                                    newselectd.push(dataArray[i].id);
                                }                           
                            }else{
                                if(!selectids.includes(dataArray[i].deleteid)){ // 删除数据
                                    newdata.push(dataArray[i]);
                                }
                            }
                        }else{
                            if(!selectids.includes(dataArray[i][this.formtable[indexstatus-1].tableHeader[0].field_name_en])){ // 删除数据
                                newdata.push(dataArray[i]);
                            }else{
                                if(dataArray[i].id){
                                    newselectd.push(dataArray[i].id);
                                }
                            }
                        }
                    }
                    this.formtable[indexstatus-1].tableData = newdata;
                    this.formtable[indexstatus-1].allTableData[pwd] = newdata;
                    if(newselectd.length > 0){
                        this.formtable[indexstatus-1].deleteData = newselectd;
                    }
                    this.$set(this.formtable, this.formtable)
                    // this.$modalSure('您确定要删除这条数据,删除后将无法恢复，请确认哦').then(() => {
                    //     for(let i=0; i< dataArray.length;i++){
                    //         if(!selectids.includes(dataArray[i][this.formtable[indexstatus-1].tableHeader[0].field_name_en])){ // 删除数据
                    //             newdata.push(dataArray[i]);
                    //         }else{
                    //             if(dataArray[i].id){
                    //                 newselectd.push(dataArray[i].id);
                    //             }
                    //         }
                    //     }
                    //     if(newselectd.length > 0){
                    //        this.handlerDeleteData(this.formtable[indexstatus-1].value, {ids: newselectd}, newdata, indexstatus);
                    //     }
                    // })
                }else{
                    this.$message.error("请选择要删除的数据")
                }
            }else if(val=='liuchengtu'){ // 查看流程图
                let tableDatasall = []
                if(this.dangqianIndex !== 1){  // 物料清单子级数据
                    let tableDatas = this.formtable[indexstatus-1].allTableData[this.parentData.wuliaobianmaid];
                    tableDatasall = tableDatas;
                    this.allgongyiTableData = tableDatasall; // 所有工艺保存到data
                }else{ // 当前为物料清单第一级
                    let alltable = this.formtable[indexstatus-1].allTableData; // 当前所有已显示出来的工艺流程数据
                    let onetable = this.formtable[indexstatus-1].allTableData[this.parentData.id]; // 第一级这里传id不传物料编码，获取一级的工艺流程
                    let childDatas2 =  this.formtable[0].gy; //当前一级的物料下的所有工艺流程数据
                    childDatas2[this.parentData.id] = onetable // 一级的工艺流程加入到所有工艺中去
                    let allgoyidata = {}
                    allgoyidata = this.mergeObjects(alltable, childDatas2);// 已显示的工艺流程和数据中的旧工艺流程比较获取最新的工艺流程所有数据
                    let endallgyList = [];
                    for(let a in allgoyidata){ // 所有最新的工艺流程数据进行出来成一维数组
                        if(allgoyidata[a] && allgoyidata[a].length > 0){
                            for(let b=0;b<allgoyidata[a].length > 0;b++){
                                endallgyList.push(allgoyidata[a][b])
                            }
                        }
                    }
                    tableDatasall = endallgyList; // 赋值
                    this.allgongyiTableData = tableDatasall; // 所有工艺保存到data
                }
                console.log("tableDatasall", tableDatasall)
                for(let i=0;i< tableDatasall.length;i++){
                    tableDatasall[i].startname = tableDatasall[i].peijianleixing + '-' + tableDatasall[i].bengongxu;
                    tableDatasall[i].endname = tableDatasall[i].peijianleixing + '-' + tableDatasall[i].daogongxu;
                    if(tableDatasall[i].daopeijianleixing){
                        console.log("tableDatasall[i].daopeijianleixing", tableDatasall[i].daopeijianleixing)
                        tableDatasall[i].endname = tableDatasall[i].daopeijianleixing + '-' + tableDatasall[i].daogongxu;
                        console.log("tableDatasall[i].endname", tableDatasall[i].endname , tableDatasall[i])
                    }
                

                }
                
                console.log("tableDatasall", tableDatasall)
                this.handlerFlowTreeData(tableDatasall)
            }
             
        },

        hadnlerNewbuildHierarchy(data) {
  // 创建一个映射表，以startname为键存储节点
  const nodeMap = {};
  
  // 首先创建所有节点
  data.forEach(item => {
    nodeMap[item.startname] = {
      ...item,
      children: []
    };
  });

  // 构建树结构
  const rootNodes = [];
  
  data.forEach(item => {
    const currentNode = nodeMap[item.startname];
    const parentNode = nodeMap[item.endname];
    
    if (parentNode) {
      parentNode.children.push(currentNode);
    } else {
      // 如果没有找到父节点，则作为根节点
      rootNodes.push(currentNode);
    }
  });

  return rootNodes;
},
buildReverseTree8(data) {
      const endToNodesMap = {};
      const startToNodeMap = {};
      
      // 构建映射关系
      data.forEach(item => {
        if (!endToNodesMap[item.endname]) {
          endToNodesMap[item.endname] = [];
        }
        endToNodesMap[item.endname].push(item);
        
        startToNodeMap[item.startname] = {
          ...item,
          children: []
        };
      });
      
      // 找出根节点（没有对应的startname的endname）
      const rootEndNames = Object.keys(endToNodesMap).filter(
        endname => !startToNodeMap[endname]
      );
      
      // 递归构建树
      const buildTree = (endname) => {
        const nodes = endToNodesMap[endname] || [];
        return nodes.map(node => {
          return {
            ...startToNodeMap[node.startname],
            children: buildTree(node.startname)
          };
        });
      };
      
      // 生成所有树
      return rootEndNames.flatMap(endname => buildTree(endname));
    },



        // 思维导图数据
        handlerFlowTreeData(tableDatasall){
            // let rowsdata = this.hadnlerAllOrtTree(JSON.parse(JSON.stringify(tableDatasall)));
            // let rowsdata = this.handlerNewOrtTree(this.rowsdatatest);
            let rowsdata = this.buildReverseTree8(tableDatasall)
            console.log("流程图树形数据：", rowsdata)
            let vueorgtree = this.hadnlerTreeData(rowsdata);
         
            this.OrgTreeData = vueorgtree;
            this.$set(this.OrgTreeData, this.OrgTreeData)
            this.dialogliucheTitle = '工艺流程图'
            this.dialogliucheVisible = true;
        },
        // 获取最后一级工序的id和到工序id
        hadnlerTreeData(rowdata){
            let treeData = this.uniqueTreeData(rowdata);
            let allData = []
            for(let i = 0; i < treeData.length; i++){
                let obj = {
                    id: treeData[i].id,
                    peijianxuhao: (Number(treeData[i].peijianxuhao) + 1),
                    shengchanzhouqi: treeData[i].shengchanzhouqi,
                    gongyinandu: treeData[i].gongyinandu,
                    laiyuan: treeData[i].laiyuan,
                    peijianleixing: this.handlerpenjiangongxu(treeData[i].peijianleixing, 1),
                    bengongxuid: treeData[i].daogongxuid,
                    bengongxu: treeData[i].daogongxu,
                    daogongxuid: '',
                    daopeijianleixing: '',
                    wuliaodanganid: treeData[i].wuliaodanganid,
                    wuliaodangan: treeData[i].wuliaodangan,
                    children:[]
                }
                obj.children.push(treeData[i])
                allData.push(obj)
            }
            return allData;
        },
        // 工艺配件类型类型获取id
        handlerpenjiangongxu(peijianleixing, index=0){
            let imdata = this.formtable[1].datadictList.peijianleixing;
            if(imdata && imdata.length > 0){
                for(let i=0;i<imdata.length;i++){
                    if(peijianleixing == imdata[i].value || peijianleixing == imdata[i].name ){
                        return index ==1 ? imdata[i].name : imdata[i].value;
                    }
                }
            }
            return '';
        },
        //工艺来源类型获取id
        handlerlaiyuan(laiyuan, index=0){
            let imdata = this.formtable[1].datadictList.laiyuan;
            if(imdata && imdata.length > 0){
                for(let i=0;i<imdata.length;i++){
                    if(laiyuan == imdata[i].value || laiyuan == imdata[i].name ){
                        return index ==1 ? imdata[i].name : imdata[i].value;
                    }
                }
            }
            return '';
        },
        // 测试方法
        // 对象key相同去重合并方法
        mergeObjects(obj1, obj2) {
            const result = { ...obj1 }; 
            // 遍历第二个对象的所有key
            for (const key in obj2) {
                if (obj2.hasOwnProperty(key)) {
                    // 如果第一个对象没有这个key，或者第一个对象中这个key对应的值为空
                    if (!result.hasOwnProperty(key) || 
                        (Array.isArray(result[key]) && result[key].length === 0) || 
                        result[key] === null || 
                        result[key] === undefined || 
                        result[key] === "") {
                        
                        // 使用第二个对象的值
                        result[key] = obj2[key];
                    } else if (Array.isArray(result[key]) && Array.isArray(obj2[key])) {
                        // 如果都是数组，需要合并数组并去重
                        const combinedArray = [...result[key]];
                        const idsInResult = new Set(result[key].map(item => item.id));
                        
                        // 添加第二个数组中不存在的元素
                        for (const item of obj2[key]) {
                            if (!idsInResult.has(item.id)) {
                                combinedArray.push(item);
                            }
                        }
                        
                        result[key] = combinedArray;
                    }
                }
            }
            
            return result;
        },
        hadnlerAllOrtTree(data){
            for (let i of data) {
                i.isEnd = true
                for (let j of data) {
                    if(i.daogongxuid == j.bengongxuid){
                        i.isEnd = false
                    }
                }
            }

            function buildTree(items, parentId = null, level = 0) {
                // 创建一个数组来存储当前父节点下的所有子节点
                let tree = [];
                // 遍历所有项，找到所有父节点为parentId的项
                let children = items.filter(item => item.daogongxuid === parentId);
                
                for (let child of children) {
                    child.alevel = level + 1; // 设置当前节点的层级
                    // 递归调用buildTree，为当前子节点找到其子节点
                    let childrenOfChild = buildTree(items, child.bengongxuid, level + 1);
                    if (childrenOfChild.length) {
                        child.children = childrenOfChild; // 将找到的子节点添加到当前节点的children属性中
                    }
                    tree.push(child); // 将当前节点添加到树中
                }
                return tree; // 返回当前父节点下的所有子节点组成的树形结构
            }

            let TreeData = [];
            for (let item of data) {
                if(item.isEnd){
                    TreeData = TreeData.concat(buildTree(data,item['daogongxuid']));
                }
            }

            return TreeData;
        },

        // 新生成思维图数据处理方法
        handlerNewOrtTree(data){
            for (let key of data) {
                if(key['daopeijianleixing']){
                    key['bengongxuid'] = key['bengongxuid'] + '-' + key['peijianleixing']
                    key['daogongxuid'] = key['daogongxuid'] + '-' + key['daopeijianleixing']
                }else{
                    key['bengongxuid'] = key['bengongxuid'] + '-' + key['peijianleixing']
                    key['daogongxuid'] = key['daogongxuid'] + '-' + key['peijianleixing']
                }
            }

            // ‘到工序’ 不在 ‘本工序’ 视为末端工序
            // 1. 遍历 data 数组
            let endMap = []; // 储存到工序id是否重复
            for (let i of data) {
                let isIn = true;
                for (let j of data) {
                    if(i.daogongxuid == j.bengongxuid){
                        isIn = false;
                    }
                }
                if(isIn){
                    if(endMap.indexOf(i.daogongxuid) == -1){
                        endMap.push(i.daogongxuid)
                    }
                }
            }

            // console.log(data);

            function buildTree(items, parentId = null, level = 0) {
                // 创建一个数组来存储当前父节点下的所有子节点
                let tree = [];
                // 遍历所有项，找到所有父节点为parentId的项
                let children = items.filter(item => item.daogongxuid === parentId);
                
                for (let child of children) {
                    child.alevel = level + 1; // 设置当前节点的层级
                    // 递归调用buildTree，为当前子节点找到其子节点
                    let childrenOfChild = buildTree(items, child.bengongxuid, level + 1);
                    if (childrenOfChild.length) {
                        child.children = childrenOfChild; // 将找到的子节点添加到当前节点的children属性中
                    }
                    tree.push(child); // 将当前节点添加到树中
                }
                return tree; // 返回当前父节点下的所有子节点组成的树形结构
            }

            let TreeData = [];

            console.log(endMap);

            for (let item of endMap) {
                TreeData = TreeData.concat(buildTree(data, item));
            }
            return TreeData;
        },
   buildReverseTreeone(data) {
  const grouped = {};
  // 按 peijianleixing 分组
  data.forEach(item => {
    const type = item.peijianleixing;
    if (!grouped[type]) {
      grouped[type] = [];
    }
    grouped[type].push(item);
  });

  const result = {};
  for (const type in grouped) {
    const items = grouped[type];
    const nodeMap = {};
    // 创建节点并存入 map
    items.forEach(item => {
      nodeMap[item.daogongxuid] = {
        ...item,
        children: []
      };
    });

    // 构建树结构
    items.forEach(item => {
      const currentNode = nodeMap[item.daogongxuid];
      const parentProcessId = item.bengongxuid;
      if (nodeMap[parentProcessId]) {
        currentNode.children.push(nodeMap[parentProcessId]);
      }
    });

    // 收集根节点（没有父节点的节点）
    const roots = [];
    for (const processId in nodeMap) {
      let hasParent = false;
      for (const item of items) {
        if (item.bengongxuid === processId) {
          hasParent = true;
          break;
        }
      }
      if (!hasParent) {
        roots.push(nodeMap[processId]);
      }
    }

    result[type] = roots;
  }

  return result;
},
    // 测试数据
   
buildOrgTreethree(data) {
  // 创建映射表：daogongxuid → 节点
  const nodeMap = new Map();
  // 创建反向映射：bengongxuid → 子节点数组
  const parentMap = new Map();

  // 第一次遍历：建立映射关系
  data.forEach(item => {
    // 转换节点结构，添加org-tree需要的字段
    const node = {
      ...item,
      label: item.daogongxu, // org-tree显示用
      children: []          // 初始化子节点
    };
    
    // 存入主映射表
    nodeMap.set(node.daogongxuid, node);
    
    // 建立反向父子关系映射
    if (!parentMap.has(node.bengongxuid)) {
      parentMap.set(node.bengongxuid, []);
    }
    parentMap.get(node.bengongxuid).push(node.daogongxuid);
  });

  // 第二次遍历：构建树结构
  const roots = [];
  nodeMap.forEach(node => {
    // 查找当前节点的父节点
    const parentNodes = parentMap.get(node.daogongxuid);
    
    if (parentNodes && parentNodes.length) {
      // 如果当前节点是其他节点的父节点，添加到对应父节点的children
      parentNodes.forEach(parentId => {
        const parent = nodeMap.get(parentId);
        if (parent && !parent.children.some(child => child.daogongxuid === node.daogongxuid)) {
          parent.children.push(node);
        }
      });
    } else {
      // 没有父节点的作为根节点
      roots.push(node);
    }
  });

  // 递归排序子节点（按peijianxuhao）
  const sortChildren = (node) => {
    if (node.children.length) {
      node.children.sort((a, b) => a.peijianxuhao - b.peijianxuhao);
      node.children.forEach(sortChildren);
    }
  };
  roots.forEach(sortChildren);

  return roots;
},

mergeTopLevel(data) {
  const map = new Map();
  const uniqueItems = [];
  const mergedItems = [];

  // 第一次遍历：分离唯一项和重复项
  data.forEach(item => {
    const key = item.daogongxuid;
    if (!map.has(key)) {
      // 记录新节点并保留首次出现位置
      map.set(key, { ...item, children: [...item.children] });
      uniqueItems.push(item);
    } else {
      // 合并children
      const existing = map.get(key);
      existing.children.push(...item.children);
      mergedItems.push(key);
    }
  });

  // 过滤出需要合并的项（保留首次出现的唯一项）
  const finalUnique = uniqueItems.filter(item => !mergedItems.includes(item.daogongxuid));
  const finalMerged = Array.from(map.values()).filter(item => mergedItems.includes(item.daogongxuid));

  // 合并结果：唯一项在前，合并项在后
  return [...finalUnique, ...finalMerged];
},

    buildTypeTree(data) {
  const typeMap = new Map();
  const nodeMap = new Map();
  const reverseMap = new Map();

  // 建立索引
  data.forEach(item => {
    // 按类型分组
    if (!typeMap.has(item.peijianleixing)) {
      typeMap.set(item.peijianleixing, new Map());
    }
    const typeNodes = typeMap.get(item.peijianleixing);

    // 创建节点映射
    if (!typeNodes.has(item.daogongxuid)) {
      typeNodes.set(item.daogongxuid, {
        ...item,
        children: [],
        types: new Set([item.peijianleixing])
      });
    }

    // 建立反向关系
    if (!reverseMap.has(item.bengongxuid)) {
      reverseMap.set(item.bengongxuid, []);
    }
    reverseMap.get(item.bengongxuid).push(item.daogongxuid);
  });
  // 为每个类型构建树
  const result = {};
  typeMap.forEach((nodes, type) => {
    // 找出根节点（没有父节点的节点）
    const roots = Array.from(nodes.values()).filter(node => 
      !reverseMap.has(node.daogongxuid) || 
      !reverseMap.get(node.daogongxuid).some(id => nodes.has(id))
    );
    // 递归构建子树
    const buildBranch = (parentId) => {
      return (reverseMap.get(parentId) || [])
        .filter(id => nodes.has(id))
        .map(id => {
          const node = nodes.get(id);
          return {
            ...node,
            children: buildBranch(node.daogongxuid)
          };
        });
    };
    result[type] = roots.map(root => ({
      ...root,
      children: buildBranch(root.daogongxuid)
    }));
  });
  return result;
},

// end
   

// 测试代码
    processDatanews(data) {
      return data.map(node => this.processNode(node))
    },

    // 处理单个节点
    processNode(node) {
      // 创建处理后的节点副本
      const processedNode = { ...node }
      
      // 处理子节点
      if (node.children && node.children.length) {
        // 去重处理
        const uniqueChildren = this.removeDuplicates(node.children)
        // 递归处理子节点
        processedNode.children = uniqueChildren.map(child => this.processNode(child))
      }

      return processedNode
    },

    // 移除同级重复项
    removeDuplicates(children) {
      const seen = new Map()
      return children.reduce((acc, current) => {
        // 生成唯一标识键
        const key = `${current.peijianleixing}_${current.bengongxuid}`
        
        // 检查是否已存在相同项
        if (!seen.has(key)) {
          seen.set(key, true)
          acc.push(current)
        }
        return acc
      }, [])
    },
  
// end

        // 根据配件类型id获取name
        handlerpenjianleixi(data, id){
            for(let i=0;i< data.length;i++){
                if(id == data[i].value){
                    return data[i].name;
                }
            }
            return ''
        },
        
        generateTreenew(data, maxDepth = 1000) {
            // 使用Map去重并建立索引
            const nodeMap = new Map();
            const bengongIndex = new Map();
            const daogongIndex = new Map();

            data.forEach(item => {
                nodeMap.set(item.id, item);
        
                // 建立bengongxu索引
                if (!bengongIndex.has(item.bengongxu)) {
                    bengongIndex.set(item.bengongxu, new Set());
                }
                bengongIndex.get(item.bengongxu).add(item.id);
                
                // 建立daogongxu索引
                if (!daogongIndex.has(item.daogongxu)) {
                    daogongIndex.set(item.daogongxu, new Set());
                }
                daogongIndex.get(item.daogongxu).add(item.id);
            });

            // 递归构建树
            const buildTree = (currentId, path = new Set(), depth = 0) => {
                if (depth > maxDepth) {
                    throw new Error(`Maximum call stack depth (${maxDepth}) exceeded`);
                }
                
                const node = nodeMap.get(currentId);
                if (!node) return null;
                
                // 检测循环引用
                if (path.has(currentId)) {
                    console.warn(`Circular reference detected at node: ${currentId}`);
                    return null;
                }
                const newPath = new Set(path).add(currentId);

                // 查找子节点
                const children = [];
                const childIds = daogongIndex.get(node.bengongxu) || new Set();
                
                childIds.forEach(childId => {
                    if (childId !== currentId) { // 避免自引用
                        const childTree = buildTree(childId, newPath, depth + 1);
                        if (childTree) {
                            children.push(childTree);
                        }
                    }
                });

                return {
                    ...node,
                    children: children.length ? children : undefined
                };
            };

            // 查找根节点(没有其他节点的daogongxu指向它的bengongxu)
            const rootNodes = [];
            nodeMap.forEach((node, id) => {
                if (!bengongIndex.has(node.daogongxu) || 
                    !Array.from(bengongIndex.get(node.daogongxu)).some(x => x !== id)) {
                    rootNodes.push(id);
                }
            });

            return rootNodes.map(rootId => buildTree(rootId)).filter(Boolean);
        },
       
        // 去重
        uniqueTreeData(treeData) {
            // 创建映射键的函数
            const createKey = (node) => {
                return [node.bengongxu, node.daogongxu, node.peijianleixing].join('|')
            }

            // 递归处理函数
            const processNode = (node) => {
                if (!node.children || !node.children.length) return node
                
                // 使用Map进行分组
                const childrenMap = new Map()
                
                // 遍历处理所有子节点
                node.children.forEach(child => {
                const processedChild = processNode(child)
                const key = createKey(processedChild)
                
                if (childrenMap.has(key)) {
                    // 合并子节点的子节点
                    const existing = childrenMap.get(key)
                    existing.children = mergeChildren(existing.children, processedChild.children)
                } else {
                    // 创建新节点并保留其他属性
                    childrenMap.set(key, { 
                    ...processedChild,
                    children: processedChild.children ? [...processedChild.children] : []
                    })
                }
                })

                return {
                ...node,
                children: Array.from(childrenMap.values())
                }
            }

            // 合并子节点数组
            const mergeChildren = (existing = [], newChildren = []) => {
                const merged = [...existing]
                const keyMap = new Map(existing.map(item => [createKey(item), item]))
                
                newChildren.forEach(child => {
                const key = createKey(child)
                if (keyMap.has(key)) {
                    const existingChild = keyMap.get(key)
                    existingChild.children = mergeChildren(existingChild.children, child.children)
                } else {
                    merged.push(child)
                    keyMap.set(key, child)
                }
                })
                
                return merged
            }

            // 处理根节点
            return treeData.map(root => processNode(root))
        },

        // 对工艺数据进行分组，并为每个起始点生成流程数组
        generateProcessFlowsnew(processData) {
            // 1. 按 peijianxuhao 分组
            const stepsBySequence = {};
            processData.forEach(item => {
                const seq = item.peijianxuhao;
                if (!stepsBySequence[seq]) {
                stepsBySequence[seq] = [];
                }
                stepsBySequence[seq].push(item);
            });
            // 2. 检查是否有 peijianxuhao: 1 的记录
            if (!stepsBySequence[1] || stepsBySequence[1].length === 0) {
                return [];
            }

            // 3. 为每个 peijianxuhao: 1 的记录生成流程
            return stepsBySequence[1].map(startItem => {
                const flow = [startItem];
                let currentSeq = 1;
                // 4. 按顺序查找后续步骤
                while (true) {
                const nextSeq = currentSeq + 1;
                if (!stepsBySequence[nextSeq]) break; // 没有后续步骤了
                
                // 查找匹配的下一步骤
                const nextSteps = stepsBySequence[nextSeq];
                const nextItem = nextSteps.find(step => 
                    step.bengongxu === flow[flow.length - 1].daogongxu
                );
                if (!nextItem) break; // 找不到匹配的下一步骤
                flow.push(nextItem);
                currentSeq = nextSeq;
                }
                return flow;
            });
        },
        handlerNewArray(data){
            const result = [];
            let currentGroup = null;
            data.forEach(item => {
                if (item.peijianxuhao === 1) {
                    currentGroup = []; // 新建分组
                    result.push(currentGroup); // 加入结果数组
                }
                if (currentGroup) { // 确保有当前分组（避免第一个元素前无分组）
                    currentGroup.push(item);
                }
            });
            return result;

        },
        handlerOrgtreeData(data, lengths){
            let newdata = JSON.parse(JSON.stringify(data));
            let endobj = data[lengths-1];
            let newobj = {
                id: endobj.id || '',
                bengongxuid: endobj.daogongxuid,
                peijianleixing: endobj.daopeijianleixing ? endobj.daopeijianleixing: endobj.peijianleixing,
                daogongxuid: '',
            }
            newdata.push(newobj)
            return newdata;
        },

       
        // 关联物料档案实体表删除接口
        handlerDeleteData(keyName, data, newdata, indexstatus){
            crudModuleBatchDelApi(keyName, data).then((res) => {
                if(res.status==200){
                    let pwid = this.parentData.wuliaobianmaid?this.parentData.wuliaobianmaid: this.parentData.id;
                    this.formtable[indexstatus-1].allTableData[pwid] = newdata;
                    // this.formtable[indexstatus-1].deleteData = newselectd;
                    if(this.keyName == 'wuliaoqingdanbiao'){
                        EventBus.$emit('event-tree-grandchild', this.formtable[indexstatus-1].allTableData[pwid], 1)
                    }
                }
            })
        },
        
        // 获取物料类别规格列表数据
        async getwuliaoleibieList(indexstatus, keyName, data={}) {
            crudModuleListApi(keyName, data).then((res) => {
                if(res.status==200){
                    let array1 = this.formtable[indexstatus-1].tableData;
                    let array2 = res.data.list;
                    let arr3 = []
                    for(let i=0;i<array2.length;i++){
                        delete array2[i].wuliaoleibiebianmaid;
                        delete array2[i].is_share;
                        delete array2[i].id;
                        array2[i].guigeneirong_two=''
                        if(array2[i].wuliaodanganid){
                            array2[i].wuliaodanganid = ''
                        }else{
                            array2[i].wuliaodanganid = ''
                        }
                        arr3.push(array2[i])
                    }
                    const mergedArray = [...array1, ...arr3];
                    const result = mergedArray.filter(
                    (item, index, self) => index === self.findIndex(t => t.guigedaima === item.guigedaima)
                    );
                    // let tabledata2 = []
                    // result.map((item)=>{
                    //     if(!item.wuliaodanganid){
                    //         item.wuliaodanganid = ''
                    //     }
                    //     tabledata2.push(item)
                    // })
                    this.formtable[indexstatus-1].tableData = result;
                }
            })
        },
       
        // 获取实体表单信息
        getTableFormInput(id, keyName) {
            crudFormInfoApi(id).then((res) => {
                let optiondata = res.data.options;
                if(keyName =='guige'){
                    for(let i=0;i<optiondata.length;i++){
                        if(optiondata[i].name=='状态'){
                            this.optionStatus = optiondata[i].options.optionItems;
                            break;
                        }
                    }
                }
            })
        },
        // 获取规格编码字典数据(添加弹窗显示)
        getGuigezidian(data, indexstatus=0){
            // 调用configDictDataApi函数，传入keyName和0作为参数
            configDictDataApi(data).then((res) => {
                 let resdata = res.data.list;
                 this.diatotal = res.data.count;
                 this.selectInfo = [
                    {
                        field_name: "代码",
                        field_name_en: "value",
                        form_value: "input",
                    },
                    {
                        field_name: "名称",
                        field_name_en: "name",
                        form_value: "input",
                    }
                 ]
                 this.selectData = []
                 let selectedlist = []
                 this.formtable[indexstatus-1].tableData.map((item)=>{
                    selectedlist.push(item.guigedaima)
                 })
                 if(selectedlist.length > 0){
                 for(let i=0;i< resdata.length;i++){
                     if(!selectedlist.includes(resdata[i].value)){
                        this.selectData.push(resdata[i])
                     }
                 }
                }else{
                    this.selectData = resdata
                }
                this.dialogVisible = true;
            })
        },
        // 获取供应商数据(添加弹窗显示)
        async getshitibiaosearch(keyName, formdata, indexstatus=0, fieldData=''){
            crudModuleListApi(keyName, formdata).then((res) => {
                if(res.status==200){
                    let resdata = res.data.list;
                    this.diatotal = res.data.count;
                    // let headerData = this.formtable[indexstatus-1].tableHeader;
                    // let headerInfo = headerData.slice(0,2)
                    // this.selectInfo = headerInfo
                   
                    let headerData = fieldData.showField;
                    let headerInfo = headerData.slice(0,2)
                    this.selectInfo = headerInfo
                    let fielseniorSearch = fieldData.seniorSearch;
                    let searchForms = {}
                    this.searchField = []
                    for(let i=0;i < fielseniorSearch.length;i++){
                        if(i < 2){
                          searchForms[fielseniorSearch[i].field_name_en] = ''
                          this.searchField.push(fielseniorSearch[i])
                        }
                    }
                    this.searchForm = searchForms
                    this.selectData = []
                    let selectedlist = []
                    this.formtable[indexstatus-1].tableData.map((item)=>{
                        selectedlist.push(item[headerInfo[0].field_name_en])
                    })
                    if(selectedlist.length > 0){
                        if(resdata.length > 0){
                            for(let i=0;i< resdata.length;i++){
                                if(!selectedlist.includes(resdata[i][headerInfo[0].field_name_en])){
                                    this.selectData.push(resdata[i])
                                }
                            }
                        }else{
                            this.selectData = []
                        }
                    }else{
                        this.selectData = resdata
                    }
                    this.dialogVisible = true;     
                }
            })
        },
        handlerxiegang(val, data){
        if(val){
          if(val.includes("/")){
            let newStr = val.replace(/\//g, "");
            if(data && data.length > 0){
              for(let i=0;i < data.length; i++){
                  if(data[i].value == newStr){
                      return data[i].name;

                  }
              }
            }else{
                return newStr;
            }
          }else{
            let newStr = val
            if(data && data.length > 0){
              for(let i=0;i < data.length; i++){
                  if(data[i].value == newStr){
                      return data[i].name;

                  }
              }
            }
          }
        }
        return ''
        },

        // 选中表格数据返回
        selectTabel(val){
            if(val && val.length > 0){
               this.formtable[this.selectDialogIndex-1].selectData = val
            }
        },
        // 搜索 返回
        handlerSearch(data){
            console.log("sarchdata：", data)
            if(this.selectName == 'guige'){
                this.guigezidian.name = data.name;
                this.getGuigezidian(this.guigezidian, this.selectDialogIndex);
            // }else if(this.selectName == this.keyName){
            //     let wldadatas = crudModuleListApi(this.keyName);
            }else{
                let shitibiaosearchForm = {...this.shitibiaosearch, ...data};
                console.log("dings:",shitibiaosearchForm)
                this.getshitibiaosearch(this.selectName, shitibiaosearchForm, this.selectDialogIndex, this.selectFiledData);
            }
        },
        // 提交数据返回
        handlerSubmit(index=0, data){

            if(index==0){ // 取消关闭弹窗
                this.dialogVisible = false;
            }else{
                if(this.selectName == 'guige'){ // 物料档案规格表
                    if(data.length > 0){
                        for(let i=0;i<data.length;i++){
                            let formobj  = {}
                            formobj = JSON.parse(JSON.stringify(this.formtable[this.selectDialogIndex-1].form));
                            formobj.guigedaima = data[i].value;
                            formobj.guigeleixing = data[i].name;
                            formobj.zhuangtai = '正常'; //{name:'正常', color:'#303030'};
                            this.formtable[this.selectDialogIndex-1].tableData.push(formobj);
                        }
                    }  
                }else{
                    if(data.length > 0){
                        for(let i=0;i<data.length;i++){
                            const keys = Object.keys(this.formtable[this.selectDialogIndex-1].form)
                            if(this.keyName =='wuliaoqingdanbiao'){ // 物料清单表
                                let formobj = JSON.parse(JSON.stringify(this.formtable[this.selectDialogIndex-1].form));
                                let pwid = this.parentData.wuliaobianmaid?this.parentData.wuliaobianmaid: this.parentData.id;
                                formobj.wuliaobianmaid = data[i].id;
                                formobj.item_depc = data[i].item_depc;
                                formobj.item_sn = data[i].item_sn
                                formobj.unit = data[i].unit;
                                formobj.unitName = data[i].unit.join(",");
                                formobj.id = ''
                                formobj.dahuodingliao = 1; // 大货定料默认选中
                                formobj.yangbandingliao = 1; // 样板定料默认选中
                                formobj.fuwuliaobianmaid = pwid;
                                this.formtable[this.selectDialogIndex-1].allTableData[pwid].push(formobj);
                                this.$set(this.formtable, this.formtable)
                                EventBus.$emit('event-tree-grandchild', this.formtable[this.selectDialogIndex-1].allTableData[pwid])
                            }else{
                                if(keys && keys.length > 0){
                                    let formobj = JSON.parse(JSON.stringify(this.formtable[this.selectDialogIndex-1].form));
                                    for(let key of keys){
                                        if(data[i][key]){
                                            if(key in data[i]){
                                                formobj[key] = data[i][key];
                                            }
                                        }
                                    }
                                    if(formobj.kehao){ // 档案客户信息表批量添加要获取客户信息的id才能把客号添加成功
                                        formobj.kehaoid = data[i].id;
                                    }
                                    if(formobj.zhuangtai==''){
                                        formobj.zhuangtai = '正常'
                                    }
                                    if(formobj.gongxudaima){
                                    formobj.gongxudaimaid = data[i].id;
                                    }
                                    this.formtable[this.selectDialogIndex-1].tableData.push(formobj);
                                }else{
                                    this.formtable[this.selectDialogIndex-1].tableData.push(data[i]);
                                }
                            }
                        }
                    }  
                }
                if(index==2){ // 确认退出关闭弹窗
                    this.dialogVisible = false;
                }
            }
        },
        // 上传文件方法
        uploadServerLog(params) {
            this.percentShow = true
            const file = params.file
            let options = {
            way: 2,
            relation_type: '',
            relation_id: '',
            eid: ''
            }
            uploader(file, 0, options)
            .then((res) => {
                // 获取上传文件渲染页面
                if (res.data.name) {
                   this.imageUrl.push(res.data)
                }
            })
            .catch((err) => {})
        },  
        handlerFilterTime(data, header){
            let datalength = header.length;
            if(data && data.length > 0 ){
                data.map((item)=>{
                    for(let i=0; i < datalength;i++){
                        if(item[header[i].field_name_en] == '0000-00-00'){
                            item[header[i].field_name_en] = '' 
                            break;
                        }
                    }
                })
                return data;
            }else{
                return data;
            }
            
        },
        mergeProcessTrees(treeData, listData) {
        // 1. 将列表数据转换为树形结构
        const listTree = this.buildTreeFromList(listData);
        // 2. 合并到主树中
        this.mergeTrees(treeData, listTree);
        return treeData;
        },

buildTreeFromList(listData) {
  // 创建节点映射表
  const nodeMap = {};
  listData.forEach(item => {
    nodeMap[item.bengongxuid] = item;
  });

  // 找出所有根节点（没有父节点的节点）
  const rootNodes = listData.filter(item => 
    !listData.some(x => x.daogongxuid === item.bengongxuid)
  );

  // 递归构建树
  return rootNodes.map(root => this.buildNode(root, nodeMap, listData));
},
buildNode(node, nodeMap, listData) {
  // 查找所有子节点
  const children = listData.filter(item => 
    item.daogongxuid === node.bengongxuid
  );

  return {
    ...node,
    children: children.map(child => this.buildNode(child, nodeMap, listData))
  };
},
findMergeNode(tree, targetId) {
    if (tree.bengongxuid === targetId) {
      return tree;
    }
    if (tree.children) {
      for (const child of tree.children) {
        const found = this.findMergeNode(child, targetId);
        if (found) return found;
      }
    }
    return null;
  },
  processMerge(tree, mainTree) {
    if (!tree) return;
    
    const mergeNode = this.findMergeNode(mainTree, tree.daogongxuid);
    if (mergeNode) {
      if (!mergeNode.children) {
        mergeNode.children = [];
      }
      mergeNode.children.push(tree);
    } else {
      // 如果没有找到合并点，作为独立分支添加到主树
      if (!mainTree.children) {
        mainTree.children = [];
      }
      mainTree.children.push(tree);
    }

    // 递归处理子节点
    if (tree.children) {
      tree.children.forEach(child => this.processMerge(child));
    }
  },
mergeTrees(mainTree, listTree) {
  // 遍历主树查找合并点

//   this.findMergeNode(tree, targetId)

  // 对listTree中的每个节点进行合并
  

  // 处理listTree中的每个顶级节点
  if (Array.isArray(listTree)) {
    listTree.forEach(tree => this.processMerge(tree, mainTree));
  } else {
    this.processMerge(listTree, mainTree);
  }
}


        
       



    }
 }

</script>
<style>


</style>

